package com.boxing.utils;

import com.boxing.bean.User;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class WebUtil {

    /**
     * 寻找响应的cookie 值
     */
    public static Object findCookie(HttpServletRequest request, String key){
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie item : cookies) {
                if (key.equals(item.getName())) {
                    return item.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 是否已登录
     */
    public static boolean isLogin(HttpServletRequest request){
        String token = (String) WebUtil.findCookie(request, "token");
        // 根据token找到user
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("token");
        String srcToken = "";
        if (user != null){
            srcToken = user.getToken();
        }
        return token != null && token.equals(srcToken);
    }

    /**
     * 获取服务的url基本地址
     * @param request    请求
     * @return           例如：http://localhost:8080/test/ ， 其中test为项目名
     */
    public static String getServerPath(HttpServletRequest request){
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";

        return basePath;
    }
    /**
     * 获取带目录的url地址
     * @param request    请求
     * @param folderName 文件夹名 ，例如：DownLoadFile
     * @return           例如：http://localhost:8080/test/DownLoadFile
     */
    public static String getServerPath(HttpServletRequest request,String folderName){
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";
        return basePath+folderName;
    }
    /**
     * 获取服务器的根路径
     * @param request    请求
     * @return           例如：/test ， 其中test为项目名
     */
    public static String getServerContextPath(HttpServletRequest request){
        String path = request.getContextPath();
        return path;
    }
}
